package com.sushengren.easyword.converters;

import com.sushengren.easyword.annotation.WordProperty;
import com.sushengren.easyword.constants.DefaultConverters;
import com.sushengren.easyword.model.WriteData;
import com.sushengren.easyword.util.ReflectUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 实体转换
 *
 * @author sushengren
 */
public class BeanConverter {

    @SuppressWarnings("unchecked")
    public static List<WriteData> beanToWriteData(Object bean) {
        List<WriteData> result = new ArrayList<>();
        if (bean instanceof Map) {
            Set<Map.Entry<String, Object>> set = ((Map) bean).entrySet();
            for (Map.Entry<String, Object> entry : set) {
                Converter converter = DefaultConverters.getConverter(AutoConverter.class.getName());
                result.add(converter.convertToWriteData(entry.getKey(), entry.getValue()));
            }
        } else {
            List<Field> fieldList = ReflectUtil.getFieldList(bean.getClass());
            for (Field field : fieldList) {
                WordProperty wordProperty = field.getAnnotation(WordProperty.class);
                String key = wordProperty == null || wordProperty.value().isEmpty()
                        ? field.getName()
                        : wordProperty.value();
                Converter converter = wordProperty == null
                        ? DefaultConverters.getConverter(AutoConverter.class.getName())
                        : DefaultConverters.getConverter(wordProperty.converter().getName());
                result.add(converter.convertToWriteData(key, ReflectUtil.getFieldValue(bean, field)));
            }
        }
        return result;
    }

}
